package com.wr.modules.system.service.impl;

import cn.mybatis.mp.core.mvc.impl.BasicDaoImpl;
import cn.mybatis.mp.core.sql.executor.chain.QueryChain;
import com.wr.common.redis.constants.CacheConstants;
import com.wr.common.core.utils.StringUtils;
import com.wr.common.redis.service.RedisService;
import com.wr.modules.system.domain.sys.config.SysConfig;
import com.wr.modules.system.mapper.MybatisBasicMapper;
import com.wr.modules.system.service.ISysConfigService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * @author MyPC
 */
@Service
@Slf4j
public class SysConfigServiceImpl extends BasicDaoImpl<SysConfig, Long> implements ISysConfigService {

    @Resource
    private MybatisBasicMapper mybatisBasicMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init() {
        log.info("初始化配置参数------------------>");
        loadingConfigCache();
    }

    @Override
    public String selectConfigByKey(String configKey) {
        String configValue = redisService.getCacheObject(getCacheKey(configKey));
        if (StringUtils.isNotEmpty(configValue)) {
            return configValue;
        }
        SysConfig retConfig = mybatisBasicMapper.get(SysConfig.class, where -> {
            where.eq(SysConfig::getConfigKey, configKey);
        });
        if (StringUtils.isNotNull(retConfig)) {
            redisService.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache() {
        List<SysConfig> configsList = mybatisBasicMapper.listAll(SysConfig.class);
        for (SysConfig config : configsList) {
            redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache() {
        Collection<String> keys = redisService.keys(CacheConstants.SYS_CONFIG_KEY + "*");
        redisService.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }
}
